package cn.servlet;

import java.io.File;
import java.io.IOException;
import java.util.List;

import javax.jws.WebService;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

@WebServlet("/upload")
@MultipartConfig
public class FileServlet extends HttpServlet {

	private static final String UPLDAD_PATH = "/upload";
	private DiskFileItemFactory factory = new DiskFileItemFactory();
    private File upload;
	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//		Part part = req.getPart("fileName");
//		part.write(getServletContext().getRealPath(UPLDAD_PATH) + File.separator + part.getSubmittedFileName());
		ServletFileUpload upload = new ServletFileUpload( factory);
		upload. setFileSizeMax(100 << 20);// 单个文件的字节数.上限
		upload. setSizeMax(1 << 30);// 单个请求中所有文件的字节数上限
		upload . setHeaderEncoding("UTF-8");
		if (upload. isMultipartContent(req)) {//判断当前请求是否是文件上传请求
		try {
		  List <FileItem> list = upload.parseRequest(req); 
		  for (FileItem fileItem : list) 
		    if (fileItem. isFormField()) {// 以前通过getParameter()方法获取的参数,为FormFi
		       System.out.println("表单字段   :" + fileItem. getFieldName() + "=" + fileItem.getString());
		     } else {
		       System.out.println("文件字段   :" + fileItem. getName());
		      fileItem. write(new File(this.upload, fileItem.getName()));
		     }
		} catch (Exception e) {
		   e. printStackTrace(); 
		}
	}
 }

	@Override
	public void init() throws ServletException {
		// TODO Auto-generated method stub
		String realPath = getServletContext().getRealPath(UPLDAD_PATH);
	    upload = new File(UPLDAD_PATH);
		if (!upload.exists()) {
			upload.mkdirs();
		}
		factory.setDefaultCharset("UTF-8");
		factory.setSizeThreshold(100 << 20);
	}
}
